package restful.struts2;

import java.util.*;

import javax.servlet.http.*;

public class CacheControl {

	private final Set<String> directives = new HashSet<String>();

	public CacheControl(Set<String> directives) {
		this.directives.addAll(directives);
	}

	public CacheControl() {
	}

	public void write(HttpServletResponse response) {
		if(notEmpty(directives)) {
			putCacheControl(directives, response);
		}
	}

	private void putCacheControl(Set<String> directives2, HttpServletResponse response2) {
		response2.setHeader("Cache-Control", join(directives2, ", "));
	}

	private boolean notEmpty(Set<String> directives) {
		return !directives.isEmpty();
	}

	private String join(Set<String> directives, String separator) {
		StringBuilder builder = new StringBuilder();
		for (String directive : directives) {
			builder.append(directive).append(separator);
		}
		return builder.toString().replaceAll(separator + "$", "");
	}

	private void add(String directive) {
		directives.add(directive);
	}

	public CacheControl noCache() {
		add("no-cache");
		return this;
	}

}
